use core::{ffi::c_char, ptr::null_mut};

use crate::{
    c::{
        osEventFlagsAttr_t, osEventFlagsClear, osEventFlagsId_t, osEventFlagsNew, osEventFlagsSet,
        osEventFlagsWait, osFlagsError, osFlagsWaitAll, osFlagsWaitAny, osRtxEventFlags_t,
    },
    utils::Store,
};

const CB_SIZE: usize = size_of::<osRtxEventFlags_t>();

pub struct EventFlags {
    cb_mem: Store<CB_SIZE>,
    id: osEventFlagsId_t,
}

impl EventFlags {
    pub const fn const_new() -> Self {
        Self {
            cb_mem: Store::const_new(),
            id: null_mut(),
        }
    }

    pub fn create(&mut self, name: &str) {
        let attr = osEventFlagsAttr_t {
            name: name.as_ptr() as *const c_char,
            cb_mem: self.cb_mem.c_ptr(),
            cb_size: CB_SIZE as u32,
            attr_bits: 0,
        };
        self.id = unsafe { osEventFlagsNew(&attr) };
        debug_assert!(self.id != null_mut(), "event falgs create fail");
    }

    pub fn set_flags(&self, flags: u32) {
        unsafe {
            osEventFlagsSet(self.id, flags);
        }
    }

    pub fn clear_flags(&self, flags: u32) {
        unsafe {
            osEventFlagsClear(self.id, flags);
        }
    }

    pub fn wait_any_flags(&self, flags: u32, timeout: u32) -> bool {
        unsafe { (osEventFlagsWait(self.id, flags, osFlagsWaitAny, timeout) & osFlagsError) == 0 }
    }

    pub fn wait_all_flags(&self, flags: u32, timeout: u32) -> bool {
        unsafe { (osEventFlagsWait(self.id, flags, osFlagsWaitAll, timeout) & osFlagsError) == 0 }
    }
}
